package com.example.http.provider.servlet;

import com.example.http.provider.bean.User;
import com.example.http.provider.common.Result;
import com.example.http.provider.common.XStreamUtil;
import com.example.http.provider.service.UserService;
import com.example.http.provider.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "xmlServlet", value = "/xmlServlet")
public class XMLServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/xml;charset=UTF-8");
        Result<User> result = new Result<>();
        try {
            String requestType = req.getParameter("requestType");
            if ("get".equals(requestType)) {
                String id = req.getParameter("id");
                User user = userService.get(Integer.valueOf(id));
                result.success(user);
            } else if ("add".equals(requestType)) {
                BufferedReader reader = req.getReader();
                String oneLine;
                StringBuilder stringBuilder = new StringBuilder();
                while ((oneLine = reader.readLine()) != null) {
                    stringBuilder.append(oneLine);
                }
                User user = XStreamUtil.fromXML(stringBuilder.toString(), User.class);
                User data = userService.add(user);
                result.success(data);
            } else {
                result.fail("requestType 不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.fail(e.toString());
        }
        PrintWriter out = resp.getWriter();
        out.println(XStreamUtil.toXML(result));
    }
}
